// 轨迹数据格式
let linePath = [];
const pathList = [];
var arrList = ['mgrArea', 'certId', 'expireDate', 'nextCheckDate', 'vehInsuredDate',
	'ownerName'
]
// 地图对象
const map = new AMap.Map("container", {
	resizeEnable: true,
	zoom: 15,
	showIndoorMap: false,
	center: [114.205173, 30.63413],
});
// 已经走了的时间
let passedTime = "00:00:00";
// 走的总时间
let totalTime = "00:00:00";
// 历史轨迹巡航器
let pathSimplifierIns = null;
// 巡航器
let navgtr = null;
// 基础播放速度
let speed = 100;
// 播放倍速
let times = 1;
// 是否为手动拉动进度条
let isOnSlider = false;
// 当前进度条的值
let sliderVal = 0;
// 播放状态
let isPlay = false;
// 开始按钮是重新开始还是继续
let playIcon = "resume";
let numSpeed = 1
const car = "https://webapi.amap.com/images/car.png";
// 数据
// let collapseData;
// let selectOptions;
let data;
const receiveData = (str) => {
	data = JSON.parse(str);
	document.getElementsByClassName('details_right_txt')[0].innerHTML = data.vehTrackInfo.vehCode + '(' +
		getDictValue(data.option.plateColor, data.vehTrackInfo.vehColor) + ')'

	for (let i = 0; i < arrList.length; i++) {
		document.getElementsByClassName('details_right_txt')[1].innerHTML = getDictValue(data.option
			.ccertState, data.ccertState)
		document.getElementsByClassName('details_right_txt')[i + 2].innerHTML = data[arrList[i]] ? data[
			arrList[i]] : '-'

	}

	// linePath = data.linePath;
	// collapseData = data.collapseData;
	// collapseColumns = collapseColumns[data.context];
	// selectOptions = data.selectOptions;
	// 初始化数据
	// initContent();
	// console.log(data)
	// data.vehTrackInfo.gpsInfoList.map((item) => {
	// 	linePath.push([item.lon, item.lat])
	// });
	AMapConvertFrom(data.vehTrackInfo.gpsInfoList)
		.then(res => {
			linePath = res.map((item) => {
				return {
					latitude: item.lat,
					longitude: item.lon,
					time: item.gpsDateTime,
					v1: item.v1
				};
			});
			init();
		}).catch((err) => {
			console.log(err);
		})
};
// 计算两个点之间的速度 km/h
const speedFun = (point1, point2, time) => {
	// point1,point2:经纬度数组，time:时间，s
	let distance = distanceFun(point1, point2);
	if (distance === 0) {
		return 0;
	} else {
		return distance / 1000 / (time / 60 / 60);
	}
};
// 修改倍速
// const setTimes = (val) => {
// 	times = val;
// 	// $('.speed-list').style.display = "none";
// 	$('.map-times').innerHTML = "倍速" + val;
// };
// 格式化时间
const getTime = (sTime) => {
	let ss;
	let mm = "00";
	let hh = "00";
	if (sTime > 60) {
		let s = sTime % 60;
		ss = s > 9 ? s : "0" + s;
		let mTime = parseInt(sTime / 60);
		if (mTime > 60) {
			let m = mTime % 60;
			mm = m > 9 ? m : "0" + m;
			hh = parseInt(mTime / 60);
		} else {
			mm = mTime > 9 ? mTime : "0" + mTime;
		}
	} else {
		ss = sTime > 9 ? sTime : "0" + sTime;
	}
	return hh + ":" + mm + ":" + ss;
};
// 计算两个坐标点之间的距离
const distanceFun = (point1, point2) => {
	// point1:[longitude,latitude]
	let p1 = new AMap.LngLat(point1[0], point1[1]);
	let p2 = new AMap.LngLat(point2[0], point2[1]);
	let distance = Math.round(p1.distance(p2));
	return distance;
};
// 初始化
const init = () => {
	let len = linePath.length;
	if (len < 2) {
		alert('没有轨迹点')
		return;
	}
	// $('.map-control').style.display = 'block';
	let startPoint = linePath[0];
	let endPoint = linePath[len - 1];

	// 添加起始点和终点
	new AMap.Marker({
		map,
		position: new AMap.LngLat(startPoint.longitude, startPoint.latitude),
		icon: new AMap.Icon({
			size: new AMap.Size(37, 51),
			image: '../../../static/img/start.png',
			imageSize: new AMap.Size(37, 51),
		}),
		offset: new AMap.Pixel(0, -26),
		anchor: "center",
	});
	new AMap.Marker({
		map,
		position: new AMap.LngLat(endPoint.longitude, endPoint.latitude),
		icon: new AMap.Icon({
			size: new AMap.Size(37, 51),
			image: '../../../static/img/end.png',
			imageSize: new AMap.Size(37, 51),
		}),
		offset: new AMap.Pixel(0, -26),
		anchor: "center",
	});


	pathList.splice(0, pathList.length);
	linePath.forEach((item) => {
		pathList.push([item.longitude, item.latitude]);
		item.stampTime = new Date(item.time).getTime(); //当前时间戳
	});
	// 下一段路程经历了多少s,intervalTime,nextDistance:下一段路程：m,nextDistance:下一段路速度：km/h
	linePath.forEach((item, i) => {
		let next = linePath[i + 1];
		if (next) {
			item.intervalTime = (next.stampTime - item.stampTime) / 1000;
			item.nextDistance = distanceFun(
				[item.longitude, item.latitude],
				[next.longitude, next.latitude]
			);
			item.nextSpeed =
				item.nextDistance / 1000 / (item.intervalTime / 60 / 60);
		}
	});
	// 订单记录总时间，hh:mm:ss
	totalTime = getTime(
		(endPoint.stampTime - startPoint.stampTime) / 1000
	);
	setPath();
};
// 开启手动拖拽
const openSlider = () => {
	isOnSlider = true;
};
// 关闭手动拖拽
const closeSlider = () => {
	isOnSlider = false;
};
const sliderChange = (newVal) => {
	let num = parseInt((newVal / 100) * pathList.length);
	let decimal = num % 1 || 0;
	navgtr.moveToPoint(num, decimal);
	pathSimplifierIns.renderLater();
};

// 开始、暂停、继续等操作
const navgControl = (action) => {
	if (action === 'pause') {
		$('.pause').style.display = 'none';
		$('.resume').style.display = '';
	} else {
		$('.pause').style.display = '';
		$('.resume').style.display = 'none';
	}
	if (action === "start") {
		sliderVal = 0;
		passedTime = "00:00:00";
		setTimeout(() => {
			navgtr[action]();
		}, 300);
	} else {
		navgtr[action]();
	}
};
// 设置巡航路线
const setPath = () => {
	AMapUI.load(
		["ui/misc/PathSimplifier", "lib/$"],
		function(PathSimplifier) {
			if (!PathSimplifier.supportCanvas) {
				console.log("当前环境不支持 Canvas！");
				return;
			}
			let len = linePath.length;
			let startPoint = linePath[0];
			let endPoint = linePath[len - 1];
			// 轨迹总数
			function onload() {
				pathSimplifierIns.renderLater();
			}

			function onerror() {
				console.log("图片加载失败！");
			}
			// 历史轨迹巡航器
			pathSimplifierIns = new PathSimplifier({
				zIndex: 100,
				//autoSetFitView:false,
				map, //所属的地图实例
				getPath: function(pathData) {
					return pathData.path;
				},
				getHoverTitle: function(pathData) {
					return pathData.index;
				},
				autoSetFitView: true,
				// 巡航器样式
				renderOptions: {
					pathNavigatorStyle: {
						initRotateDegree: -90, // 图标的默认角度
						width: 32,
						height: 20,
						autoRotate: true,
						lineJoin: "round",
						content: PathSimplifier.Render.Canvas.getImageContent(
							car,
							onload,
							onerror
						),
						fillStyle: null,
						strokeStyle: null,
						lineWidth: 1,
						pathLinePassedStyle: {
							lineWidth: 6,
							strokeStyle: "#2cdf4d",
						},
					},
					pathLineStyle: {
						lineWidth: 6,
						strokeStyle: "#2e9c08",
					},
					pathLineHoverStyle: {
						lineWidth: 0,
						borderWidth: 0,
					},
					pathLineSelectedStyle: {
						lineWidth: 6,
						borderWidth: 0,
						strokeStyle: "#2e9c08",
					},
					pathTolerance: 0,
					keyPointTolerance: -1,
					renderAllPointsIfNumberBelow: 0, //绘制路线节点，如不需要可设置为-1
				},
			});

			//历史轨迹巡航器设置数据
			pathSimplifierIns.setData([{
				name: "轨迹",
				path: pathList,
			}, ]);
			pathSimplifierIns.setFitView(-1);

			let startSpeed = speedFun(
				pathList[0],
				pathList[1],
				startPoint.intervalTime
			);
			startSpeed === 0 && (startSpeed = 0.1);

			//对第一条线路（即索引 0）创建一个巡航器
			navgtr = pathSimplifierIns.createPathNavigator(0, {
				loop: false, //循环播放
				speed: startSpeed * times, //巡航速度，单位千米/小时
			});
			// console.log(startPoint);
			//构建自定义信息窗体
			let infoContent = `<p class="info-window">时间：<span>${startPoint.time} `;
			let infoWindow = new AMap.InfoWindow({
				anchor: "bottom-center",
				content: infoContent,
			});

			infoWindow.open(map, pathList[0]);
			// 移动过程中
			navgtr.on("move", function() {
				playIcon = "resume";
				let idx = this.getCursor().idx; //走到了第几个点
				let tail = this.getCursor().tail; //至下一个节点的比例位置
				let totalIdx = idx + tail;

				// that.popUp = trackList[idx]
				document.getElementsByClassName('track-mid_text_first')[0].innerHTML = linePath[idx]
					.longitude
				document.getElementsByClassName('track-mid_text_first')[1].innerHTML = linePath[idx]
					.latitude
				document.getElementsByClassName('track-mid_text_first')[2].innerHTML = linePath[idx]
					.v1 + 'KM/h'
				document.getElementsByClassName('track-top_time')[0].innerHTML = '定位时间：' + linePath[idx]
					.time

				// that.popUp.latitude = trackList[idx].latitude
				// that.popUp.speed = trackList[idx].v1
				// that.popUp.time = trackList[idx].time
				// 计算下一个距离速度
				let point = linePath[idx];
				if (idx < len - 1) {
					point.nextSpeed === 0 && (point.nextSpeed = 0.1);
					navgtr.setSpeed(point.nextSpeed * times);
				}

				// 剩余公里数，窗体随时移动展示
				point &&
					point.time &&
					infoWindow.setContent(
						`<p class="info-window">时间：<span>${point.time}`
					);
				infoWindow.open(map, navgtr.getPosition());
				// 进度条实时展示tail
				!isOnSlider && setSlider((totalIdx / (len - 1)) * 100);
				// 已经播放时间
				// let sTime = (pointObj.stampTime-startStampTime)/1000;
				let sTime = parseInt(
					(((endPoint.stampTime - startPoint.stampTime) / 1000) *
						sliderVal) /
					100
				);

				passedTime = getTime(sTime);
				// 如果到头了，回到初始状态
				if (navgtr.isCursorAtPathEnd()) {
					playIcon = "start";
					isPlay = false;
					sliderVal = 100;
					passedTime = totalTime;
				}
			});

			navgtr.on("start resume", function() {
				navgtr._startTime = Date.now();
				navgtr._startDist = this.getMovedDistance();
			});
			navgtr.on("stop pause", function() {
				navgtr._movedTime = Date.now() - navgtr._startTime;
				navgtr._movedDist =
					this.getMovedDistance() - navgtr._startDist;
			});
		}
	);
};

// 坐标系转换
const AMapConvertFrom = (locations, type = "gps") => {
	return new Promise((resolve, reject) => {
		const pages = Math.ceil(locations.length / 500);
		if (pages == 0) {
			resolve([])
			return;
		}
		let res = [];
		let resIndex = 0;
		let resState = true;
		for (let i = 0; i < pages; i++) {
			const locationsSlice = locations.slice(500 * i, 500 * (i + 1));
			const LngLat = locationsSlice.map((item) => [item.lon, item.lat]);
			AMap.convertFrom(LngLat, type, function(status, result) {
				resIndex++;
				if (result.info === "ok") {
					// console.log(locations, result.locations);
					res[i] = locationsSlice.map((item, index) => {
						item.lon = result.locations[index].lng;
						item.lat = result.locations[index].lat;
						return item;
					});
				} else {
					resState = false;
				}
				// console.log(res instanceof Array)
				if (resIndex == pages) {
					if (resState) {
						res = flat(res, 2);
						// console.log(JSON.stringify(res))
						resolve(res);
					} else {
						reject();
					}
				}
			});
		}
	});
};

const flat = (arr, deep) => {
	if (deep > 0)
		return arr.reduce((pre, cur) => pre.concat(Array.isArray(cur) ? flat(cur, deep - 1) : cur), [])
	return arr.slice()
}



// 根据ClassName/Id获取dom
const $ = (str) => {
	if (str.startsWith('.')) {
		return document.getElementsByClassName(str.slice(1))[0]
	}
	if (str.startsWith('#')) {
		return document.getElementById(str.slice(1));
	}
	return null;
}
/**
 * 以下为滑块事件
 */
// 修改滑块当前值
const setSlider = (val) => {
	$('.slider-color').style.width = val + '%';
	handle.style.left = val + '%'; // 根据鼠标位置移动滑块
	if (isOnSlider) {
		sliderChange(val);
	}
}
let startX;
let handle = $('.slider-wrapper');
let slider = $('.slider-box');
handle.addEventListener('touchstart', (event) => {
	openSlider();
	startX = event.changedTouches[0].clientX - handle.offsetLeft; // 保存初始位置
}, false);
document.addEventListener('touchmove', (event) => {
	if (isOnSlider) {
		var newLeft = event.changedTouches[0].clientX - startX;
		if (newLeft < 0) {
			newLeft = 0;
		} else if (newLeft > slider.offsetWidth) {
			newLeft = slider.offsetWidth;
		}
		setSlider(newLeft / slider.offsetWidth * 100);
	}
}, false);
document.addEventListener('touchend', (event) => {
	if (isOnSlider) {
		var newLeft = event.changedTouches[0].clientX - startX;
		if (newLeft < 0) {
			newLeft = 0;
		} else if (newLeft > slider.offsetWidth) {
			newLeft = slider.offsetWidth;
		}
		setSlider(newLeft / slider.offsetWidth * 100);
		closeSlider();
	}
}, false);

$('.map-times').addEventListener('click', () => {
	$('.speed-list').style.display = 'block';
})


// 调节倍数
function clickSpeed(index) {
	if (index == 1 && numSpeed != 1) {
		numSpeed = numSpeed - 1
		document.getElementById('times-num').innerHTML = numSpeed
	}
	if (index == 2) {
		numSpeed = numSpeed + 1
		document.getElementById('times-num').innerHTML = numSpeed

	}
	times = numSpeed
}

// 关闭
function closeClack() {
	document.getElementsByClassName('track')[0].style.display = 'none'
}

// 运单信息
function waybillInfor() {
	uni.navigateTo({
		url: '/pages/carMonitor/trackInquire?formSearch=' + JSON.stringify(data)
	})
}

// 字典
function getDictValue(list, value) {
	let target = list.filter((v) => v.dictKey == value)[0];
	return (target && target.dictValue) || "";
}


// 轨迹信息
function trackInfor() {
	if (linePath.length == 0) {
		alert('暂无轨迹')
	} else {
		document.getElementsByClassName('track-mid_text_first')[0].innerHTML = linePath[0]
			.longitude
		document.getElementsByClassName('track-mid_text_first')[1].innerHTML = linePath[0]
			.latitude
		document.getElementsByClassName('track-mid_text_first')[2].innerHTML = linePath[0]
			.v1 + 'KM/h'
		document.getElementsByClassName('track-top_time')[0].innerHTML = '定位时间：' + linePath[0].time

		document.getElementsByClassName('track')[0].style.display = 'inline-block'
	}
}

// 信息查询
// function seach() {
// 	uni.postMessage({
// 		data: {
// 			order: false
// 		}
// 	});
// }

// 信息查询
function seach() {
	uni.navigateTo({
		url: '/pages/carMonitor/index'
	})
}
